//
//  Upload.m
//  UpLoadImageTest7.7
//
//  Created by zhangtao on 15/7/7.
//  Copyright (c) 2015年 siou. All rights reserved.
//

#import "Upload.h"

#define kTimeOut 5.0f

@implementation Upload

-(id) initWithURL:(NSString *)mURL {
    self = [super init];
    
    URL = mURL;   //请求的URL
    Boundary = @"AaS8HJ";  //分界符
    
    return self;
}

-(BOOL)Post:(NSMutableURLRequest *)requests andDic:(NSDictionary *)params withImage:(NSString *)img{
    
    
    //创建URL
   
    NSMutableURLRequest *request = requests;//[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.26.110.70/bzz/home/api/v1.0/api_user_pictures.php?function_name=addPicture"]];
   
    
    // 设置content-type
    NSString * contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",Boundary];
    
    //添加普通字段
    NSArray * keys = [params allKeys];
    NSMutableData *body = [NSMutableData data];
    for (int i=0;i<[keys count];i++) {
        NSString * key = [keys objectAtIndex:i];
        if (![key isEqualToString:@"pic"]) {
            
            //添加分界符：--AaS8HJ
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", Boundary]
                              dataUsingEncoding:NSUTF8StringEncoding]];
            
            //声明一个字段：  content-disposition: form-data; name="字段名"
            [body appendData:[[NSString stringWithFormat:
                               @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key]
                              dataUsingEncoding:NSUTF8StringEncoding]];
           
            //字段的值
            [body appendData:[[NSString stringWithFormat:@"%@\r\n", [params objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    
    
    // 加入一个图片
    NSData *imageData = [NSData dataWithContentsOfFile:img];//UIImagePNGRepresentation(img);
    if (imageData) {
        
        ////添加分界符：--AaS8HJ
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", Boundary]
                          dataUsingEncoding:NSUTF8StringEncoding]];
        
        //声明一个字段
        //content-disposition: form-data; name="pic"; filename="image.png"
        //Content-Type: image/png
        //NSString *va = @"123";
        NSString *str1 = @"Content-Disposition: form-data; name=";
        NSString *str2 = self.goodId;
        NSString *str3 = @"; filename=\"image.png\"\r\n";
        NSString *str = [[str1 stringByAppendingString:str2]stringByAppendingString:str3];
        [body appendData:[str
                          dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/png\r\n\r\n"
                          dataUsingEncoding:NSUTF8StringEncoding]];
        
        //添加图片的二进制内容
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"]
                          dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    
    // post请求结尾的分界线，注意，这里是--AaS8HJ--，前后都有小横线
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", Boundary]
                      dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:body];
    [request setValue:contentType forHTTPHeaderField:@"content-Type"];
    
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    
    // request
    [NSURLConnection connectionWithRequest:request delegate:self];
    NSLog(@"request:%@",request);
    return YES;
}


#pragma mark - NSURLConnection delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"请求成功%@",response);
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"请求失败");
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"data:%@",str);
}
@end






//static NSString *boundaryStr = @"--"; //分隔字符串
//static NSString *randomIDStr;     //本次上传标志字符串
//static NSString *uploadID;         //上传（pho）脚本中，接收文字字段
//
//-(instancetype)init{
//    self = [super init];
//    if (self) {
//        randomIDStr = @"itcastupload";
//        uploadID = @"uploadFile";
//    }
//    return self;
//}
//
//#pragma mark - 成员方法
//- (void)uploadFile:(NSString *)path fileName:(NSString *)fileName completion:(void (^)(NSString *string))completion
//{
//    NSURL *url = [NSURL URLWithString:@"http://120.26.110.70/bzz/home/api/v1.0/api_give_pictures.php"];
//    NSURLRequest *request = [self requestForUploadURL:url uploadFileName:fileName localFilePath:path];
//    NSURLSession *session = [NSURLSession sharedSession];
//    
//    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//        NSLog(@"%@ %@",result,[NSThread currentThread]);
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (completion) {
//                completion(@"下载完成");
//            }
//        });
//    }] resume];
//}
//
////拼接字符串
//-(NSString *)bottomString{
//    NSMutableString *strM = [NSMutableString string];
//    
//    [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
//    [strM appendString:@"Content-Disposition: form-data; name=\"submit\"\n\n"];
//    [strM appendString:@"Submit\n"];
//    [strM appendFormat:@"%@%@--\n", boundaryStr, randomIDStr];
//    
//    NSLog(@"底部字符串：%@", strM);
//    return [strM copy];
//}
//
///** 指定全路径文件的mimeType */
//- (NSString *)mimeTypeWithFilePath:(NSString *)filePath
//{
//    // 1. 判断文件是否存在
//    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
//        return nil;
//    }
//    
//    // 2. 使用HTTP HEAD方法获取上传文件信息
//    NSURL *url = [NSURL fileURLWithPath:filePath];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    
//    // 3. 调用同步方法获取文件的MimeType
//    NSURLResponse *response = nil;
//    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
//    
//    return response.MIMEType;
//}
//
///** 上传文件网络请求 */
//- (NSURLRequest *)requestForUploadURL:(NSURL *)url uploadFileName:(NSString *)fileName localFilePath:(NSString *)filePath
//{
//    // 0. 获取上传文件的mimeType
//    NSString *mimeType = [self mimeTypeWithFilePath:filePath];
//    if (!mimeType) return nil;
//    
//    // 1. 拼接要上传的数据体
//    NSMutableData *dataM = [NSMutableData data];
////    [dataM appendData:[[self topStringWithMimeType:mimeType uploadFile:fileName] dataUsingEncoding:NSUTF8StringEncoding]];
//    // 拼接上传文件本身的二进制数据
//    [dataM appendData:[NSData dataWithContentsOfFile:filePath]];
//    [dataM appendData:[[self bottomString] dataUsingEncoding:NSUTF8StringEncoding]];
//    
//    // 2. 设置请求
//    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:kTimeOut];
//    // 1> 设定HTTP请求方式
//    requestM.HTTPMethod = @"POST";
//    // 2> 设置数据体
//    requestM.HTTPBody = dataM;
//    // 3> 指定Content-Type
//    NSString *typeStr = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", randomIDStr];
//    [requestM setValue:typeStr forHTTPHeaderField:@"Content-Type"];
//    // 4> 指定数据长度
//    NSString *lengthStr = [NSString stringWithFormat:@"%@", @([dataM length])];
//    [requestM setValue:lengthStr forHTTPHeaderField:@"Content-Length"];
//    
//    return [requestM copy];
//}
//

























//@end
